#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import sys

class ModifyHosts(object):

    def __CheckHostsPath(self):
        return os.path.join(os.getenv("SystemDrive"),'/Windows/System32/drivers/etc/hosts')

    #在脚本运行目录 放置的要新增的hosts记录内容
    def __ReadNewHosts(self):
        with open(os.path.join(self.cur_file_dir(),'hosts.txt'),'r') as f:
            return f.readlines()
        
    def cur_file_dir(self):       
        path = sys.path[0]        
        if os.path.isdir(path):
            return path
        elif os.path.isfile(path):
            return os.path.dirname(path)

    def __GetFileObj(self,handleType):
        path = self.__CheckHostsPath()
        return open(path,handleType)

    def __ReadSysHosts(self):
        with self.__GetFileObj('r') as f:
            return f.readlines()
                
    def __WriteSysHosts(self,newHosts):
        with self.__GetFileObj('w') as f:
            return f.write(newHosts)

    def __GetDomain(self,str):
        result=''
        if not str.startswith('#'):
            infoArray=str.strip().split()
            if len(infoArray)>=2:
                result=infoArray[1]
        return result    

    #拿出要过滤掉的域名 hosts中注释的行不做操作
    def __GetBeFilterDomain(self,newHosts):    
        beFilterDomain=[]    
        for newH in newHosts:
                if self.__GetDomain(newH)!='' and self.__GetDomain(newH) not in beFilterDomain:
                    beFilterDomain.append(self.__GetDomain(newH))
        return beFilterDomain


    def __ModeifyHosts(self,newHosts):                
        currentHosts = self.__ReadSysHosts()
        print(u'\n当前hosts总行数 %s ' % len(currentHosts))

        beFilterDomain=self.__GetBeFilterDomain(newHosts)

        beRemove=[]
        for cruuentH in currentHosts:
            for newH in beFilterDomain:
                if self.__GetDomain(cruuentH)!='' and newH==self.__GetDomain(cruuentH):
                    beRemove.append(cruuentH)
                    
        print(u'\n检测到 %s 个记录将被删除' % len(beRemove))
        print(beRemove)
        for r in beRemove:
            currentHosts.remove(r)
            
        #追加本次新增的hosts 
        for n in newHosts:
            currentHosts.append(n)            
        print(u'\n追加后hosts总行数 %s ' % len(currentHosts))

        self.__WriteSysHosts(''.join(currentHosts))            
        print(u'\n操作成功!')

    def Run(self):
        newHosts = self.__ReadNewHosts()    
        if(len(newHosts) > 0):
            self.__ModeifyHosts(newHosts)
        else:
            print(u'hosts len is zero!')




if __name__ == '__main__':
    m = ModifyHosts()
    m.Run()
